#!/bin/sh
# PCP QA Test No. 1900
# Test bpf PMDA with valgrind.
#
# Copyright (c) 2022 Red Hat.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.check
. ./common.bpf

_check_valgrind
_pmdabpf_check
valgrind --version | sed -e 's/valgrind-//' | awk -F. '$1 < 3 || ($1 == 3 && $2 < 19) {exit 1}' || \
    _notrun "this test requires valgrind 3.19+"

status=1

cat <<EOF >$tmp.conf
# Installed by PCP QA test $seq on `date`
[biolatency.so]
enabled=true

[runqlat.so]
enabled=true

# no execsnoop.so for this test, thank you
EOF
_pmdabpf_tryload $tmp.conf

_cleanup()
{
    cd $here
    _pmdabpf_cleanup
    $sudo rm -rf $tmp $tmp.*
}

trap "_cleanup; exit \$status" 0 1 2 3 15

_filter_logs()
{
    # need sudo here because of _run_valgrind --sudo
    $sudo tee -a $seq_full \
    | sed \
	-e '/ Debug: /d' \
	-e '/ Info: /d' \
	-e '/WARNING: unhandled eBPF command 28/d' \
	-e '/WARNING: unhandled eBPF command 36/d' \
    # end
}

cat >$tmp.suppress <<End-of-File
# The libbpf probes to test for whether the kernel supports certain features
# do not fully initialize the attr struct passed in the syscall.
# This is outside the control of PCP.  There is an upstream libbpf issue filed:
#
#   https://github.com/libbpf/libbpf/issues/845
{
   libbpf missing attr missing expected_attach_type field initialization
   Memcheck:Param
   bpf(attr->expected_attach_type)
   fun:syscall
   ...
}
{
   libbpf missing attr missing prog_ifindex field initialization
   Memcheck:Param
   bpf(attr->prog_ifindex)
   fun:syscall
   ...
}
End-of-File

# preliminaries ...
# - install bpf PMDA so we get bpf in the default PMNS
# - setup up a minimalist "works everywhere" bpf.conf
#
_prepare_pmda bpf
_pmdabpf_install $tmp.conf
_pmdabpf_wait_for_metric

pmda=$PCP_PMDAS_DIR/bpf/pmda_bpf,bpf_init

grind_extra="--suppressions=$tmp.suppress"
echo && echo "== Running pmdabpf with valgrind"
_run_valgrind --sudo pminfo -L -K clear -K add,157,$pmda -dmtT bpf.disk bpf.runq 2>&1 \
| _filter_logs

cd $here
for metric in bpf.disk.all.latency bpf.runq.latency
do
    echo && echo "== Checking if metric $metric has any values"
    _run_valgrind --sudo src/wait_for_values -L -K clear -K add,157,$pmda -w 10000 $metric 2>&1 \
    | _filter_logs
done


# success, all done
status=0
exit
